var express = require('express');
var router = express.Router();
var random = require("../utils/randomUser") //随机生成用户名方法
// token 验证
var jwt = require('jsonwebtoken');
var Ctoken = require('../utils/token');
//创建用户时间 默认生日时间
var { createUserDate, createBirth } = require('../utils/createDate')
// 生成用户id
var get_id_string = require('../utils/setId')
// des 加解密
var { decryptByDES } = require('../utils/idnumberDes')

// 导入用户模型
const User = require('../model/uaerModel')


// 用户新增注册
router.post("/addUsers", async function (req, res) {
  let passWord = decryptByDES(req.body.passWord, 'xilixili&register&jiangzichen&passWord&WXMiLpdhTvssHB')
  let body = {
    userName: req.body.userName,
    phone: req.body.phone,
    passWord: passWord,
  }
  // 如果 前端没传用户名 就随机生成
  if (req.body.userName == '' || req.body.userName == null) {
    body.userName = random('嘻-', 5)
  }
  const userdata = await User.find()
  body.sex = '0' // 保密
  body.introduction = '本宝宝还没有简介呢'
  body.userImg = '/userimg2022.jpg' //初始默认头像
  body.createUserDate = createUserDate()
  body.createBirth = createBirth()
  body.userId = get_id_string() + (userdata.length + 1)

  // 设置超管
  if (req.body.phone && req.body.phone == '18307106535') {
    body.Administrator = '0'
  } else {
    body.Administrator = '2'
  }

  const data = await User.find().where({
    phone: body.phone
  })

  if (data.length != 0) {
    res.send({
      code: 500,
      success: false,
      msg: "该用户已注册，请前往登录"
    })
  } else {
    //插入数据
    User.create(body).then((data) => {
      res.send({
        code: 200,
        success: true,
        msg: "注册成功，请前往登录"
      })
    }).catch((err) => {
      res.send({
        code: 500,
        success: false,
        msg: "注册失败，请稍后再试"
      })
    });
  }
})

// 用户登录并返回token
router.post('/login', async function (req, res, next) {
  let passWord = decryptByDES(req.body.passWord, 'xilixili_login_jiangzichen_passWord_qazMlpoi0987hGCnn')
  let bady = {
    phone: req.body.phone,
    passWord: passWord,
  }
  //登录前查询数据库有无此账号
  const dataUser = await User.find().where({
    phone: req.body.phone
  })
  if (dataUser.length == 0) {
    res.send({
      code: 500,
      success: false,
      msg: "该用户没有注册。请先前往注册"
    })
    return
  }
  // 验证密码
  if (dataUser.length != 0 && dataUser[0].passWord !== passWord) {
    res.send({
      code: 500,
      success: false,
      msg: "密码错误，请重新验证"
    })
    return
  }

  Ctoken.setToken(bady).then((data) => {
    let CObj = {
      code: 200,
      msg: "登录成功",
      token: data,
      success: true,
      userInfo: dataUser[0],
    }
    res.json(CObj);
  });
})

// 更新用户头像
router.post('/updateUserimg', async function (req, res, next) {
  await User.updateOne({ userId: req.body.userId, phone: req.body.phone }, { userImg: req.body.userImg }).then(data => res.send({
    code: 200,
    msg: "用户头像更新成功",
    success: true,
    data
  })).catch((err) => {
    res.send({
      code: 500,
      success: false,
      msg: "用户头像更新失败",
      data: err
    })
  });

})

// 更新用户信息
router.post('/updateUserInfo', async function (req, res, next) {
  await User.updateOne(
    { userId: req.body.userId, phone: req.body.phone },
    {
      $set: {
        userName: req.body.userName,
        sex: req.body.sex,
        createBirth: req.body.createBirth,
        introduction: req.body.introduction,
      },
      $currentDate: { updateDate: createUserDate() }
    }).then(async data => {
      const dataobj = await User.find().where({
        userId: req.body.userId, phone: req.body.phone
      })
      res.send({
        code: 200,
        msg: "用户信息更新成功",
        success: true,
        data: dataobj[0]
      })
    }).catch((err) => {
      res.send({
        code: 500,
        success: false,
        msg: "用户信息更新失败",
        data: err
      })
    });

})

// 查询管理员
router.get('/getadminlist', async function (req, res, next) {
  User.find({ Administrator: '1' }).then(data => {
    res.send({
      code: 200,
      msg: "管理员列表查询成功",
      success: true,
      data: data
    })
  }).catch((err) => {
    res.send({
      code: 500,
      success: false,
      msg: "管理员列表查询失败",
      data: err
    })
  })
})

// ------------后台管理系统接口-------------
// 登录
router.post('/admin/login', async function (req, res, next) {
  let passWord = decryptByDES(req.body.passWord, 'xilixili_adminlogin_jiangzichen_passWord_sfewt23r%dsfs')
  let bady = {
    phone: req.body.phone,
    passWord: passWord,
  }
  //登录前查询数据库有无此账号
  const dataUser = await User.find().where({
    phone: req.body.phone
  })
  if (dataUser.length == 0) {
    res.send({
      code: 500,
      success: false,
      msg: "没有该账号信息"
    })
    return
  }
  if (dataUser[0].Administrator == '2') {
    res.send({
      code: 500,
      success: false,
      msg: "您无权限访问管理后台"
    })
    return
  }
  // 验证密码
  if (dataUser.length != 0 && dataUser[0].passWord !== passWord) {
    res.send({
      code: 500,
      success: false,
      msg: "密码错误，请重新验证"
    })
    return
  }
  Ctoken.setToken(bady).then((data) => {
    let CObj = {
      code: 200,
      msg: "登录成功",
      token: data,
      success: true,
      userInfo: dataUser[0],
    }
    res.json(CObj);
  });
})

module.exports = router;
